//
//  XCFPSMonitor.swift
//  XCFPSMonitor
//
//  Created by mac on 2025/2/17.
//

import Foundation
import UIKit

//FPS监控
class XCFPSMonitor {
    
    static let shared = XCFPSMonitor()
    
    private var displayLink: CADisplayLink?
    private var lastTimestamp: CFTimeInterval = 0
    private var frameCount: Int = 0
    private var fps: Int = 0
    private let fpsThreshold: Int = 30 // 设置帧率阈值
    
    var onUpdateFps: ((Int)->Void)?
    
    private init(){}
    
    func start() {
        displayLink = CADisplayLink(target: self, selector: #selector(update))
        displayLink?.add(to: .main, forMode: .common)
    }
    
    func stop() {
        displayLink?.invalidate()
        displayLink = nil
    }
    
    @objc private func update() {
        let currenttimestamp = CACurrentMediaTime()
        
        if lastTimestamp == 0 {
            lastTimestamp = currenttimestamp
        }
        
        frameCount += 1
        if (currenttimestamp - lastTimestamp) >= 1.0 {
            fps = frameCount
            frameCount = 0
            lastTimestamp = currenttimestamp
            onUpdateFps?(fps)
            
            // 检测卡顿
            if fps < fpsThreshold {
                print("卡顿检测：当前FPS为 \(fps)，低于阈值 \(fpsThreshold)。")
                print("堆栈信息：")
                print(Thread.callStackSymbols.joined(separator: "\n"))
            }
        }
    }
    
    
}
